<template>
  <div id="app">
    <div>
      <span>图书名称:</span>
      <input type="text" v-model.trim="name" @change="jdgBook" />
    </div>
    <div>
      <button :disabled="isTrue" @click="addBook">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>图书名称</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>
        <books-tr ref="input" v-for="item in list" :key="item.id" :item="item" :list="list" @delBook="delBook" @change="change" :jdgTrue="jdgTrue" />
      </table>
    </div>
  </div>
</template>
<script>
import BooksTr from './components/BooksTr.vue'

// import moment from 'moment'

import { getListAPI } from '@/api/getListAPI.js'
import { delBookAPI } from '@/api/delBookAPI.js'
import { jdgBookAPI } from '@/api/jdgBookAPI.js'
// import { jdgIdBook } from '@/api/jdgIdBook.js'
import { addBookAPI } from '@/api/addBookAPI.js'
import { changeBookAPI } from '@/api/changeBookAPI.js'

export default {
  data () {
    return {
      list: [],
      name: '',
      edit: 0,
      isTrue: false,
      jdgTrue: false,
      id: null
    }
  },
  created () {
    this.getList()
  },
  methods: {
    async getList () {
      const { data: res } = await getListAPI()
      this.list = res
      if (this.list.length === 1) {
        this.jdgTrue = true
      } else {
        this.jdgTrue = false
      }
    },
    async delBook (e) {
      const { data: res } = await delBookAPI(e)
      if (res.status === 200) console.log(res)
      this.getList()
    },
    async jdgBook () {
      const { data: res } = await jdgBookAPI(this.name)
      if (res.status === 1) {
        this.isTrue = true
        alert('图书存在！！！')
        this.name = ''
      }
      this.isTrue = false
    },
    async addBook () {
      if (this.edit === 0) {
        // console.log('addBook')
        const { data: res } = await addBookAPI(this.name)
        if (res.status === 200) console.log(res)
        this.name = ''
        this.getList()
      } else if (this.edit === 1) {
        // console.log('changeBook')
        // console.log(this.id)
        // console.log(this.name)
        const { data: res } = await changeBookAPI(this.id, this.name)
        if (res.status === 200) alert('修改成功')
        this.edit = 0
        this.name = ''
        this.getList()
      }
    },
    change (e) {
      this.id = e[0]
      this.name = e[1]
      this.edit = e[2]
      // console.log(this.edit)
      // console.log(this.$refs.input.add())
      /* this.$nextTick(() => {
        console.log(this.$refs.input.add())
      }) */
    }
    /* async jdgId () {
      console.log(this.id)
      const { data: res } = await jdgIdBook(this.id)
      console.log(res)
    } */
  },
  components: {
    BooksTr
  }
}
</script>

BooksTr
